package org.example.leetcode;


import java.util.Stack;

/**
 * @version 1.0.0
 * @author: lynn
 * @description:
 * @date: 2021/7/27 11:27
 */
public class LC25 {
    public static void main(String[] args) {
        ListNode listNode=new ListNode(1);
        listNode.next=new ListNode(2);
        listNode.next.next=new ListNode(3);
        listNode.next.next.next=new ListNode(4);
        listNode.next.next.next.next=new ListNode(5);
        LC25 reverseKListNode=new LC25();
        reverseKListNode.reverseKGroup(listNode,3);
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head==null|| head.next==null) return head;
        int localK=k;
        Stack<ListNode> stack=new Stack<>();
        ListNode curNode=head;
        while (curNode!=null){
            localK--;
            stack.push(curNode);
            curNode=curNode.next;
        }
        if (stack.size()<k) return head;

        ListNode dummyNode =new ListNode(0);
        ListNode tail=dummyNode;
        while (stack.size()>0){
            tail.next=stack.pop();
            tail=tail.next;
        }

        tail.next=reverseKGroup(curNode,k);
        return dummyNode.next;
    }

    private static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }


}
